package com.celebriosoftware.client.receiver;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.celebriosoftware.client.MainActivity;

public class DownloadReceiver extends BroadcastReceiver {

	private MainActivity activity = null;
	
	public DownloadReceiver() {
	}
	public DownloadReceiver(Activity activity) {
		this.activity = (MainActivity) activity;
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onReceive(Context context, Intent intent) {
		DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
		long fileId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
		//Launch it
		try {// if it does not have any application to open this content, it usually crashes
			Intent intent2 = new Intent(Intent.ACTION_VIEW);
			String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(manager.getUriForDownloadedFile(fileId).toString());
			String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
			intent2.setDataAndType(manager.getUriForDownloadedFile(fileId), mimetype);
			activity.startActivity(intent2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}
